package com.shujia.jdbc.pool;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;

public class ShujiaConnectionPool {

    private static Properties prop = new Properties();

    // 连接池容量大小
    private static final int POOL_SIZE = 10;

    // key是连接对象, value表示是否在使用, true 表示在使用, false不在使用
    private static Map<Connection, Boolean> connections = new HashMap<>();

    static {
        try {
            InputStream is = ShujiaConnectionPool.class.getClassLoader()
                    .getResourceAsStream("config\\jdbc.properties");

            prop.load(is);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /*
    获取连接
     */
    public static ShujiaConnection getConnection() throws SQLException {
        // 获取键值对的数量, 保存的连接数量
        int size = connections.size();


        if (size < POOL_SIZE) {
            // 创建连接并返回
            Connection connection = DriverManager.getConnection(prop.getProperty("url"), prop);
            connections.put(connection, true);
            return new ShujiaConnection(connection);
        }

        // 查找空闲的连接并返回
        if (connections.containsValue(false)) {
            // 连接池里面有空闲的线程
            // 获取空闲线程并返回
            Set<Map.Entry<Connection, Boolean>> entries = connections.entrySet();
            for (Map.Entry<Connection, Boolean> entry : entries) {
                Connection key = entry.getKey();
                Boolean value = entry.getValue();
                if (!value) {
                    // 连接被占用
                    connections.put(key, true);
                    return new ShujiaConnection(key);
                }
            }

        }
        throw new SQLException("线程池暂时没有空闲连接");
    }

    /*
    把连接对象的value改为false, 标识未使用
     */
    public static void close(Connection connection) {
        connections.put(connection, false);
    }


}